package com.sweetcircle.controller;

import com.sweetcircle.annotation.CheckValue;
import com.sweetcircle.annotation.FieldNote;
import com.sweetcircle.annotation.GlobalInterceptor;
import com.sweetcircle.config.MinioConfig;
import com.sweetcircle.domain.vo.ResponseVO;
import com.sweetcircle.exception.BusinessException;
import com.sweetcircle.utils.AnanUtils;
import com.sweetcircle.utils.Constants;
import com.sweetcircle.utils.FileUploadUtils;
import io.minio.GetObjectArgs;
import io.minio.GetObjectResponse;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/file")
public class FileUploadDownloadController extends ABaseController {


    @Resource
    private MinioConfig minioConfig;

    @Resource
    private MinioClient minioClient;


    // 获取文件
//    @RequestMapping("/static")
//    @GlobalInterceptor(checkParams = true)
//    public void download(@CheckValue(required = true) @FieldNote(value = "文件名") String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
//        AnanUtils.readFile(response, fileName);
//    }

    @GetMapping("/avatar")
    @GlobalInterceptor(checkParams = true)
    public void avatar(@CheckValue(required = true) @FieldNote(value = "用户ID") @RequestParam(value = "userId") String userId,
                       @CheckValue(required = true) @FieldNote(value = "文件名") @RequestParam(value = "fileName") String fileName, HttpServletResponse response) throws Exception {
        AnanUtils.readAvatarFile(response, userId, fileName);
    }


    @PostMapping("/avatar")
    @GlobalInterceptor(checkParams = true,checkLogin = true)
    public ResponseVO avatarUpload(@CheckValue(required = true)@FieldNote(value = "用户ID") String userId, MultipartFile file) throws Exception {
        String projectPath = System.getProperty("user.dir");
        File filePath = new File(projectPath + "/file/images/avatar");
        File file2 = new File(filePath + File.separator + userId + File.separator + file.getOriginalFilename());
        file.transferTo(file2);
        return successResponseVO("上传成功");
    }


    // 处理文件上传
    @PostMapping("/upload")
    public ResponseVO handleFileUpload(@RequestParam("file") MultipartFile file) {
        String uploadDirectory = System.getProperty("user.dir") + "/file/";
        String fileName = file.getOriginalFilename();
        String[] split = fileName.split("\\.");
        String fileSuffix = split[split.length - 1];
        if (AnanUtils.containsElement(Constants.IMAGE_SUFFIX_LIST, fileSuffix)) {
            uploadDirectory = uploadDirectory + "/images/";
        }
        if (AnanUtils.containsElement(Constants.VIDEO_SUFFIX_LIST, fileSuffix)) {
            uploadDirectory = uploadDirectory + "/video/";
        }
        if (file.isEmpty()) {
            return errorResponseVO(new BusinessException(400, "文件不能为空 请选择一个文件上传！"), null);
        }
        try {
            // 保存上传的文件到指定目录
            Path destination = Paths.get(uploadDirectory, StringUtils.cleanPath(file.getOriginalFilename()));
            File file1 = new File(String.valueOf(destination));
            String filename = file.getOriginalFilename();
            if (file1.exists()) {
                filename = "A" + filename;
                destination = Paths.get(uploadDirectory, StringUtils.cleanPath(filename));
            }
            Files.copy(file.getInputStream(), destination);  // 保存文件
            return successResponseVO("文件上传成功", filename);
        } catch (IOException e) {
            e.printStackTrace();
            return errorResponseVO(new BusinessException(400, "文件上传失败"), null);
        }

    }

    // 文件下载
    @RequestMapping("/download")
    public ResponseEntity<byte[]> downloadFile(@RequestParam("fileName") String fileName, HttpServletResponse response) throws IOException {
        String uploadDirectory = System.getProperty("user.dir") + "/file/";
        String[] split = fileName.split("\\.");
        String fileSuffix = split[split.length - 1];
        if (AnanUtils.containsElement(Constants.IMAGE_SUFFIX_LIST, fileSuffix)) {
            uploadDirectory = uploadDirectory + "/images/";
        }
        if (AnanUtils.containsElement(Constants.VIDEO_SUFFIX_LIST, fileSuffix)) {
            uploadDirectory = uploadDirectory + "/video/";
        }

        File file = new File(uploadDirectory, fileName);
        if (!file.exists()) {
            throw new BusinessException(400, "文件未找到：" + fileName);
        }

        byte[] bytes = Files.readAllBytes(file.toPath());

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"");
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(bytes);
    }

    @RequestMapping("/minio/static")
    public void minioGetStatic(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            GetObjectArgs args = GetObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(fileName)
                    .build();
            GetObjectResponse object = minioClient.getObject(args);
            byte[] bytes = object.readAllBytes();
            response.getOutputStream().write(bytes);
        } catch (Exception e) {
            throw new BusinessException(400, "文件上传失败" + e.getMessage());
        }

    }

    @RequestMapping("/minio/upload")
    public ResponseVO minioUpload(@RequestParam("file") MultipartFile file) {
        try {
            String fileName = FileUploadUtils.extractFilename(file);
            InputStream inputStream = file.getInputStream();
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(fileName)
                    .stream(inputStream, file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();

            minioClient.putObject(args);
            String s = minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
            return successResponseVO("文件上传成功", s);

        } catch (Exception e) {
            throw new BusinessException(400, "文件上传失败" + e.getMessage());
        }

    }


    @RequestMapping("/minio/download")
    public ResponseEntity<byte[]> miniodownload(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            GetObjectArgs args = GetObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(fileName)
                    .build();
            GetObjectResponse object = minioClient.getObject(args);
            byte[] bytes = object.readAllBytes();

//            response.setHeader("Content-Disposition","attachment; filename=\"" + fileName + "\"");
//            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//            response.getOutputStream().write(bytes);

            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(bytes);

        } catch (Exception e) {
            throw new BusinessException(400, "文件上传失败" + e.getMessage());
        }

    }


}

